from typing import Any, Optional, List, Union
from dotenv import load_dotenv
from flask import Response, jsonify

from do.vo import RespResult
from .sm4 import encode_sm4, decode_sm4
from .config import workdir
import os


# 自定义返回JSON请求
def from_result(code: int = 200, data: Union[dict, list, None] = None, message: str = "") -> Response:
    if data is None:
        data = []

    result = RespResult(code=code, success=code == 200, data=data, message=message)
    return jsonify(result.model_dump())


def safe_load_dotenv(path):
    encodings = ["utf-8", "gbk", "latin1", "utf-16"]
    for encoding in encodings:
        try:
            load_dotenv(path, encoding=encoding)
            # print(f"Successfully loaded with {encoding}")
            return True
        except UnicodeDecodeError:
            continue
    raise ValueError("Failed to load .env file with any encoding")


def get_env(env_var_name: str) -> str:  # Rename parameter to avoid shadowing
    if workdir is None:
        raise RuntimeError("Environment variable WORKDIR is not set")

    safe_load_dotenv(os.path.join(workdir, "config", ".env"))

    env_value = os.getenv(env_var_name)

    if env_value is None:
        raise ValueError(f"Missing {env_var_name} environment variable")

    return env_value
